package com.sqfw.project.wp.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

@Service
public class RedisService {


    @Autowired
    private RedisTemplate redisTemplate;
//    private static double size = Math.pow(2, 32);

    /**
     * 判断缓存中是否有对应的value
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 删除对应的value
     *
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 写入缓存
     *
     * @param key        缓存key
     * @param value      缓存value
     * @param expireTime 过期时间，秒
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime) {
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        operations.set(key, value);
        redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
        return true;
    }

    /**
     * 原子递增
     *
     * @param key        键
     * @param expireTime 过期时间，秒
     * @return
     */
    public Long incr(final String key, Long expireTime) {
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        Long increment = operations.increment(key);
        redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
        return increment;
    }

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }

}
